<!-- src/views/Permission/component/permission.vue -->
<template>
  <div class="permission-management">
    <h2>权限管理</h2>

    <!-- 搜索表单 -->
    <el-form :model="searchForm" inline>
      <el-form-item label="权限名">
        <el-input
          v-model="searchForm.permissionName"
          placeholder="请输入权限名"
          clearable
          @keyup.enter="handleSearch"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-button type="primary" @click="handleAddPermission" icon="Plus">新增权限</el-button>

    <!-- 表格 -->
    <el-table
      :data="permissionStore.permissions"
      style="width: 100%; margin-top: 20px;"
      border
      v-loading="permissionStore.loading"
      stripe
    >
      <el-table-column prop="id" label="权限ID" width="180" align="center"></el-table-column>
      <el-table-column prop="permissionName" label="权限名称" width="150" align="center"></el-table-column>
      <el-table-column prop="permissionCode" label="权限标识" width="150" align="center"></el-table-column>
      <el-table-column prop="type" label="权限类型" width="120" align="center">
        <template #default="{ row }">
          {{ getPermissionTypeLabel(row.type) }}
        </template>
      </el-table-column>
      <el-table-column prop="url" label="资源路径" width="200" align="center"></el-table-column>
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" align="center">
        <template #default="{ row }">
          {{ row.createTime ? row.createTime.replace('T', ' ') : '' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)" type="primary">编辑</el-button>
          <el-button
            size="small"
            @click="handleToggleStatus(row)"
            :type="row.status === 1 ? 'danger' : 'success'"
          >
            {{ row.status === 1 ? '禁用' : '启用' }}
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="permissionStore.total"
      style="margin-top: 20px; text-align: right;"
    ></el-pagination>

    <!-- 弹窗表单 -->
    <el-dialog
      :title="operationType === 'add' ? '新增权限' : '编辑权限'"
      v-model="dialogFormVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="form"
        :rules="formRules"
        label-width="80px"
        label-position="right"
      >
        <el-form-item label="权限名" prop="permissionName">
          <el-input v-model="form.permissionName" :disabled="operationType === 'edit'" />
        </el-form-item>
        <el-form-item label="权限标识" prop="permissionCode">
          <el-input v-model="form.permissionCode" />
        </el-form-item>
        <el-form-item label="权限类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择权限类型">
            <el-option
              v-for="item in permissionTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="资源路径" prop="url">
          <el-input v-model="form.url" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { usePermissionStore } from '@/stores/permission'
import { ElMessage, ElMessageBox } from 'element-plus'

const permissionStore = usePermissionStore()

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

// 搜索相关
const searchForm = ref({
  permissionName: ''
})

// 表单弹窗控制
const dialogFormVisible = ref(false)
const form = ref({
  permissionName: '',
  permissionCode: '',
  type: 1,
  url: '',
  status: 1
})

// 权限类型选项
const permissionTypes = [
  { value: 1, label: '菜单' },
  { value: 2, label: '按钮' },
  { value: 3, label: '接口' }
]

// 表单验证规则
const formRules = {
  permissionName: [
    { required: true, message: '请输入权限名', trigger: 'blur' }
  ],
  permissionCode: [
    { required: true, message: '请输入权限标识', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择权限类型', trigger: 'change' }
  ]
}

// 操作类型：add / edit
const operationType = ref('add')
const editingPermissionId = ref(null)

// 加载数据
onMounted(() => {
  permissionStore.fetchPermissions(currentPage.value, pageSize.value)
})

// 新增权限
const handleAddPermission = () => {
  operationType.value = 'add'
  form.value = {
    permissionName: '',
    permissionCode: '',
    type: 1,
    url: '',
    status: 1
  }
  editingPermissionId.value = null
  dialogFormVisible.value = true
}

// 编辑权限
const handleEdit = (row) => {
  operationType.value = 'edit'
  editingPermissionId.value = row.id
  form.value = {
    permissionName: row.permissionName,
    permissionCode: row.permissionCode,
    type: row.type,
    url: row.url,
    status: row.status
  }
  dialogFormVisible.value = true
}

// 删除权限
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定删除权限 ${row.permissionName} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const result = await permissionStore.deletePermission(row.id)
    if (result.success) {
      ElMessage.success('删除成功')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 切换权限状态
const handleToggleStatus = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.status === 1 ? '禁用' : '启用'}权限 ${row.permissionName} 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const result = await permissionStore.togglePermissionStatus(row.id)
    if (result.success) {
      ElMessage.success('状态切换成功')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '状态切换失败')
    }
  }
}

// 提交表单
const submitForm = async () => {
  try {
    let result
    if (operationType.value === 'add') {
      result = await permissionStore.addPermission(form.value)
    } else {
      result = await permissionStore.updatePermission(editingPermissionId.value, form.value)
    }

    if (result.success) {
      ElMessage.success('操作成功')
      dialogFormVisible.value = false
    }
  } catch (error) {
    ElMessage.error(error.message || '操作失败')
  }
}

// 分页事件
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  // 直接调用搜索方法，不需要判断搜索框是否为空
  handleSearch(1, val)
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  // 直接调用搜索方法，不需要判断搜索框是否为空
  handleSearch(val, pageSize.value)
}

// 搜索功能
const handleSearch = async (page = 1, size = pageSize.value) => {
  try {
    // 直接调用 searchPermissionsByPermissionName 方法，传入空字符串
    await permissionStore.searchPermissionsByPermissionName(searchForm.value.permissionName.trim(), page, size)
    currentPage.value = page
  } catch (error) {
    ElMessage.error('搜索失败: ' + error.message)
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.value.permissionName = ''
  currentPage.value = 1
  // 直接调用搜索方法，传入空字符串
  handleSearch(currentPage.value, pageSize.value)
}

// 获取权限类型标签
const getPermissionTypeLabel = (type) => {
  const typeObj = permissionTypes.find(item => item.value === type)
  return typeObj ? typeObj.label : ''
}
</script>

<style scoped lang="scss">
.permission-management {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;

  .el-table {
    margin-top: 20px;
  }

  .el-pagination {
    margin-top: 20px;
    text-align: right;
  }
}
</style>